<template>
  <van-sticky>
    <Header title="问卷记录"/>
    <van-cell title="总分:" class="totalScores">{{scores}}</van-cell>
    <van-row class="wjhead">
      <van-col span="3">序号</van-col>
      <van-col span="13">评价内容</van-col>
      <van-col span="8">分数</van-col>
    </van-row>
  </van-sticky>

  <div>
    <van-cell-group v-for="(item, index) in evaluateList.description" :key="index">
      <van-cell  center  class="context">
        <van-row style="color: #9a9b9d; background-color: #fdfdfe;" class="selectScore">
          <van-col span="3" style="text-align: center;align-content: center;">
            <span  style="text-align: center;align-content: center;">{{index+1}}</span>
          </van-col>
          <van-col span="13" style="align-content: center;">{{ item }}</van-col>
          <van-col span="8" style="text-align: right;align-content: center;" class="wjscores">
            <van-field v-if="evaluateList.questionType[index] === 0" is-link v-model="evaluateList.score[index]" placeholder="点击评分" style="text-align: right;align-content: center; background-color: inherit !important;" @click="selectScore(index)" readonly/>
            <span v-else></span>
          </van-col>
        </van-row>
        <div v-if="evaluateList.questionType[index] === 1">
          <van-field
              type="textarea"
              v-model="message[tkList-1-index]"
              placeholder="请输入留言"
              rows="3"
              autosize
              maxlength="50"
              show-word-limit
              class="suggest"
              :readonly="stauts === '2'"
              :error-message="filedContext[index]"/>
        </div>
      </van-cell>
    </van-cell-group>
    <van-cell>听课图片上传</van-cell>
    <div class="tkImage">
      <van-uploader
          v-model="fileData"
          multiple
          async
          :max-count="5"
          :after-read="afterRead"
          :before-read="beforeRead"
          :before-delete="beforeDelete"
          :readonly="stauts === '2'"
      />
    </div>
    <van-row calss="foot_button">
      <van-col span="12"><van-button v-if="stauts !== '2'"   type="primary"  @click="handelSubmit">提交</van-button></van-col>
      <van-col span="12"><van-button v-if="stauts !== '2'"   type="primary" @click="handleUpdate">保存</van-button></van-col>
    </van-row>

  </div>

  <van-popup v-model:show="showPicker" position="bottom">
    <van-picker
        show-toolbar
        :columns="scoreData"
        @cancel="showPicker = false"
        @confirm="onConfirm"
    />
  </van-popup>

</template>

<script setup>
import { useRoute ,useRouter} from "vue-router/dist/vue-router";
import {
  getUploadUrlListenClassUrl,
  initAddTkUrl,
  initUpdateTkUrl,
  submitTkUrl
} from "/@/api/new_module/listen_class/tkTable";
import 'vant/es/popup/style';
import axios from "axios";
import {Dialog, Toast} from "vant";
import 'vant/lib/index.css'
import {onBeforeRouteLeave} from "vue-router";
import {onMounted, reactive,ref} from "vue";
import {deleteFile, submitIamge, updateTkUrl} from "../../../../api/new_module/listen_class/tkTable";

const message = reactive([])
const route = useRoute();
const router = useRouter();
const ind = ref(null);
const fileUrl = ref(null)
const fileData = ref([]);
const fileList = ref([]);
const filedContext = ref([]);
const tkID = route.query.tkId;
const stauts = route.query.stauts;
const tkList = ref(0)
const  showPicker = ref(false);
const scores = ref(0);
const scoreData = [1, 2, 3, 4, 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
const evaluateList = reactive({
  description:[],
  score:[],
  questionType:[]
})
let fileLists = reactive([])
let initLen = reactive(0);
let clic = ref(false);
let sub = ref(false)

const initData = async (tkID)=>{
  const data = await initUpdateTkUrl(tkID);
  tkList.value = data.response.value.tkDefineVo.tkDetailsList.length;
  for (let i = 0; i < data.response.value.tkDefineVo.tkDetailsList.length; i++)
  {
    evaluateList.description.push(data.response.value.tkDefineVo.tkDetailsList[i].description)
    if(data.response.value.tkDefineVo.tkDetailsList[i].score != null)
    {
      evaluateList.score.push(data.response.value.tkDefineVo.tkDetailsList[i].score)
    }else {
      evaluateList.score.push("")
    }
    evaluateList.questionType.push(data.response.value.tkDefineVo.tkDetailsList[i].questionType)

  }
  fileData.value = data.response.value.tkTableVo.fileData ? data.response.value.tkTableVo.fileData.map(item => {
    item.url = import.meta.env.VITE_APP_ADDR + item.onlineUrl
    return item;
  }) : []
  initLen = fileData.value.length
  //上传文件路径
  fileUrl.value = getUploadUrlListenClassUrl(data.response.value.tkTableVo.tkId, data.response.value.tkDefineVo.year)

  for(let i = 0; i < evaluateList.score.length; i++)
  {
    const score = parseInt(evaluateList.score[i], 10);
    if (!isNaN(score)) {
      scores.value += score;
    }
  }
  console.log(fileUrl.value)
  console.log( "fileData.value", fileData.value)
  console.log("qqq",stauts)

}

//删除文件
const beforeDelete = async(file,index) => {
  console.log(2222222222)
  console.log(fileData.value)
  await deleteFile(fileData.value[index.index].fileId,fileData.value[index.index].fileName).then((res)=>{
    if(res.data.code === 0)
    {
      Toast(res.data.msg)
      fileData.value.splice(index.index, 1);
      return true
    }else {
      Toast("删除失败")
      return false
    }
  }).catch((err)=>{})

}

//上传文件
const beforeRead = (file) => {
  console.log(file);
  console.log(fileData.value)
  if (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'){
    const formData = new FormData();
    formData.append('file', file, file.name);
    console.log("formData", formData);
    submitIamge(fileUrl.value, formData)
        .then((response) => {
          if(response.data.code !== 0)
          {
            Toast('上传失败，请重新上传')
            return false;
          }
          Toast(response.data.msg)
          fileLists.push({
            file: file.file,
            targetname: response.data.target,
            id: response.data.id
          });
          console.log("fileLists", fileLists);
          console.log('Upload successful:', response);
          // 更新 fileData，以显示上传的图片
          fileData.value.push({
            fileId: response.data.id,
            fileName: response.data.target,
            srcFileName: file.name,
            onlineUrl: `/jwfilepath/listenClass/23/${tkID}/${response.data.target}`,
            url: import.meta.env.VITE_APP_ADDR+`/jwfilepath/listenClass/23/${tkID}/${response.data.target}`
          });
          console.log("fileData", fileData.value)
          return true;
        })
  } else {
    Toast('请上传 jpg 或 png 或 gif 格式图片');
    return false;
  }
}

// 选择分数
const selectScore = (index) => {
  if(stauts !== '2' )
  {
    showPicker.value = true;
  }
  ind.value = index;
  console.log(typeof ind.value)

}

//获取分数
const onConfirm =  (value) => {
  evaluateList.score[ind.value] = value;
  // 使用 nextTick 确保评分数据的更新及时反映在页面上
  nextTick(() => {
    console.log(typeof evaluateList.score[ind.value]);
  });
  showPicker.value = false;
  scores.value = 0;
  for(let i = 0; i < evaluateList.score.length; i++)
  {
    const score = parseInt(evaluateList.score[i], 10);
    if (!isNaN(score)) {
      scores.value += score;
    }
  }
}

//提交评价
const handelSubmit = () => {
  let answer = {};
  let i = 1;
  let j = 1;
  let status = true;
  console.log("filedContext.value",filedContext.value)

  if(fileLists.length < 2)
  {
    //文件数量校验
    Toast.fail('请上传至少两张图片')
  }
  else {
    for(let k = 0; k < evaluateList.questionType.length; k++)
    {
      if(evaluateList.questionType[k] === 0)
      {
        //分数校验
        if(evaluateList.score[k] === "")
        {
          let i = k + 1;
          Toast('第'+i+'个问题未进行评分')
          status = false;
          break
        }
        answer[`score${i}`] = evaluateList.score[k];
        i++;
      }else if(evaluateList.questionType[k] === 1)
      {
        answer[`suggest${j}`] = message[j-1];
        j++;
      }
    }
    answer.tkId = tkID
    console.log("filedContext.value",filedContext.value)
    console.log(answer)
    if(status === true){
      Dialog.confirm({
        title: '提交',
        message: '确定要提交吗？',
      }).then(async () => {
        await submitTkUrl(answer).then((res) =>{
          sub.value = true;
          Toast(res.data.msg)
          router.back();
        }).catch((err) => {})
      }).catch((err) => {})
    }
  }
};

//保存评价
const handleUpdate = async () =>{
  let answer = {};
  let i = 1;
  let j = 1;
  for(let k = 0; k < evaluateList.questionType.length; k++)
  {
    if(evaluateList.questionType[k] === 0)
    {
      answer[`score${i}`] = evaluateList.score[k];
      i++;
    }else if(evaluateList.questionType[k] === 1)
    {
      answer[`suggest${j}`] = message[j-1];
      j++;
    }
  }
  answer.tkId = tkID
  Dialog.confirm({
    title: '保存',
    message: '确定要保存吗？',
  }).then(async () => {
    await updateTkUrl(answer).then((res) =>{
      sub.value = true;
      Toast(res.data.msg)
      router.back();
    }).catch((err) => {})
  }).catch((err) => {})
}

onBeforeRouteLeave((to, from, next)=>{
  console.log(stauts)
  if(stauts === '2')
  {
    clic.value = true;
  }
  if(clic.value === false && sub.value === false)
  {
    Dialog.confirm({
      closeOnPopstate: false,
      title: '提示',
      message: '问卷信息还未提交或保存，是否退出',
      confirmButtonColor : '#007aff',
      cancelButtonColor: '#007aff',
    }).then( async () => {
      next();
    }).catch( () => {
      next(false);
    });
  }else {
    next();
  }
})

onMounted(()=>{
  initData(tkID)
})
</script>

<style scoped lang="less">

.context{
  padding: 20px 0px 20px 0px;
  //margin: 1vw;

}
.totalScores{
  font-size: 4.5vw;
  padding-right: 15vw;
  //color: #2b95ef;
}
.wjhead{
  color: #7a7a83;
  background-color: #fdfdfe;
  text-align: center;
  height: 10vw;
  align-content: center;
  margin-bottom: 0;

}

/deep/.van-field__control{
  align-content: center;
  text-align: center;
}

/deep/.van-field__body{
  width: 15vw;
  margin-left: 5vw;
}

.wjbutton{
  /*width: 5vw;*/
  height: 5vw;
  border-radius: 100%;
  border-color: #2bc1ef;
  background-color: #2bc1ef;
  align-content: center;
  text-align: center;
  width: 15vw;
  margin-left: 5vw;
  /*margin-left: 5vw;*/
}


/deep/.suggest{
  padding: 0 5vw;
  width: 95vw;

  .van-field__body{
    width: 80vw;
    margin-left: 5vw;
  }

  .van-field__control{
    text-align: left;
  }
}

.tkImage{
  background-color: #fdfdfe;
  padding: 5vw;
  border-top: 1px solid #9b9b9f;
  border-bottom: 1px solid #9b9b9f;
}

/deep/.van-button--normal {
  width: 40vw;
  margin-left: 5vw;
  border-radius: 20px;
  margin-top: 10px;
}
.van-row{
  background-color: white;
}


</style>
